package cn.bearspark.common.parse.host;

import cn.bearspark.common.parse.Context;
import lombok.EqualsAndHashCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * 带有主机 ip 地址的字符串的上下文类
 *
 * @author f
 */
@EqualsAndHashCode(callSuper = true)
public class HostTextContext extends Context {

    private static final Logger LOGGER = LoggerFactory.getLogger(HostTextContext.class);

    /**
     * 主机的 ip 地址
     */
    public static final String HOST;

    static {
        String host = null;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            String candidateHost = "127.0.0.1";
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());
                for (InetAddress inetAddress : inetAddresses) {
                    if (inetAddress.isLoopbackAddress()) {
                        continue;
                    }
                    if (!inetAddress.isSiteLocalAddress()) {
                        continue;
                    }
                    String hostAddress = inetAddress.getHostAddress();
                    if (hostAddress.startsWith("192.168")) {
                        host = hostAddress;
                    } else {
                        candidateHost = hostAddress;
                    }
                }
            }
            if (host == null) {
                host = candidateHost;
            }
        } catch (Exception e) {
            host = "127.0.0.1";
            LOGGER.error("get host address error", e);
        }
        HOST = host;
    }

    public HostTextContext() {
    }

    public HostTextContext(String url) {
        this();
        super.setBody(url);
    }

}
